//
//  KLUpdateViewModel.m
//  KoalaUtilKit
//
//  Created by Tommy on 15/1/16.
//  Copyright (c) 2015年 Koala Team. All rights reserved.
//

#import "KLUpdateViewModel.h"
#import "KLIUpdate.h"
#import "KLMacro.h"
#import "KLLog.h"

@interface KLUpdateViewModel ()
@property(nonatomic,strong)id<KLIUpdate> update;

@end


@implementation KLUpdateViewModel

- (instancetype)initWithModel:(Class)modelCls service:(id<KLIUpdate>)update{
    if(self = [super initWithModelCls:modelCls]){
        _update = update;
    }
    return self;
}

- (RACCommand*)checkUpdateCmd{
    return [[RACCommand alloc]initWithSignalBlock:^RACSignal *(id input) {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            RACDisposable *disposable = [[_update checkUpdate] subscribeNext:^(id x) {
                if([x isKindOfClass:[self.model class]]){
                    [self.model copyFrom:x];
                }else{
                    KLLogError(@"update not unrecognized");
                }
                KLRACSend(x);
            } error:^(NSError *error) {
                [subscriber sendError:error];
            } completed:^{
                [subscriber sendCompleted];
            }];
            return disposable;
        }];
    }];
}
//send updateModel
- (RACSignal*) hasNewVersion{
    return [[[[RACSignal combineLatest:@[RACObserve(self.model,forceUpdate),RACObserve(self.model,recommendUpdate)]]and]ignore:@(NO)]map:^id(id value) {
        return self.model;
    }];
}
- (KLUpdateModel*) updateModel{
    return self.model;
}


@end
